package cloud.xiguapi.ubas.service.impl;

import cloud.xiguapi.ubas.analysis.advertising.BlacklistProvinceAdvertisingAnalysis;
import cloud.xiguapi.ubas.common.ApiResult;
import cloud.xiguapi.ubas.common.Pager;
import cloud.xiguapi.ubas.entity.BlacklistAdvertising;
import cloud.xiguapi.ubas.exceptions.ApiException;
import cloud.xiguapi.ubas.mapper.BlacklistAdvertisingMapper;
import cloud.xiguapi.ubas.service.IAdvertisingService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @author 大大大西西瓜皮🍉
 * date: 2021-5-20 下午 08:46
 * desc:
 */
@Service("advertisingService")
@Slf4j
@Transactional(readOnly = true, rollbackFor = ApiException.class)
public class BlacklistAdvertisingServiceImpl implements IAdvertisingService<BlacklistAdvertising> {

    private final BlacklistAdvertisingMapper blacklistAdvertisingMapper;

    private final BlacklistProvinceAdvertisingAnalysis blacklistProvinceAdvertisingAnalysis;

    @Autowired
    public BlacklistAdvertisingServiceImpl(BlacklistAdvertisingMapper blacklistAdvertisingMapper, BlacklistProvinceAdvertisingAnalysis blacklistProvinceAdvertisingAnalysis) {
        this.blacklistAdvertisingMapper = blacklistAdvertisingMapper;
        this.blacklistProvinceAdvertisingAnalysis = blacklistProvinceAdvertisingAnalysis;
    }

    @Override
    public ApiResult<Pager<BlacklistAdvertising>> selectPage(long current, long size) {
        log.info("广告数据统计查询, 参数: current = {}, size = {}", current, size);
        IPage<BlacklistAdvertising> page = blacklistAdvertisingMapper.selectPage(new Page<>(current, size));
        return ApiResult.success(Pager.<BlacklistAdvertising>builder()
                .current(page.getCurrent())
                .size(page.getSize())
                .total(page.getTotal())
                .records(page.getRecords())
                .build());
    }

    @Override
    public ApiResult<Object> analysis(String path) {
        log.info("广告数据统计");
        try {
            blacklistProvinceAdvertisingAnalysis.analysis(path);
            return ApiResult.success(Optional.empty(), "广告数据统计完成");
        } catch (Exception e) {
            log.error("广告数据统计分析失败, 原因:\n {}", e.getMessage());
            return ApiResult.failed("广告数据统计分析失败");
        }
    }
}
